﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using TestMySqlConnetPoll;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraSplashScreen;
using View;
using DevExpress.XtraGrid.Views.Base;
using System.Threading;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.Skins;

namespace NewStation
{
    /// <summary>
    /// 日报表界面
    /// </summary>
    public partial class FrmDailyTable : DevExpress.XtraEditors.XtraForm
    {
        private BandedGridView view;
        private DailyReportTable dailyReport;
        private string strDefaultDType;
        //前一次所选设备类型
        private string strPerSelectGroupCaption = string.Empty;
        private string[] customProArr = new string[] { "最大值", "最小值", "平均值" };

        //绑定数据表
        private DataTable dailyDataTable;
        private int colCount;
        private DateTime dt;


        public FrmDailyTable(string strDType)
        {
            InitializeComponent();
            strDefaultDType = strDType;
            dailyReport = new DailyReportTable();
            view = this.DevDataGrid.MainView as BandedGridView;
            LoadDTypeList(); //加载所有设备类型
            listView_Pro.BackColor = this.BackColor;
            dtPicker.CalendarTitleBackColor = this.BackColor;
           

            view.OptionsView.ColumnAutoWidth = false;
            view.OptionsView.ShowColumnHeaders = false;                         //因为有Band列了，所以把ColumnHeader隐藏
            view.OptionsView.ShowGroupPanel = false;                            //如果没必要分组，就把它去掉
            view.OptionsView.EnableAppearanceEvenRow = false;                   //是否启用偶数行外观
            view.OptionsView.EnableAppearanceOddRow = true;                     //是否启用奇数行外观
            view.OptionsView.ShowFilterPanelMode = ShowFilterPanelMode.Never;   //是否显示过滤面板
            view.OptionsCustomization.AllowColumnMoving = false;                //是否允许移动列
            view.OptionsCustomization.AllowColumnResizing = false;              //是否允许调整列宽
            view.OptionsCustomization.AllowGroup = false;                       //是否允许分组
            view.OptionsCustomization.AllowFilter = false;                      //是否允许过滤
            view.OptionsCustomization.AllowSort = true;                         //是否允许排序
            view.OptionsSelection.EnableAppearanceFocusedCell = true;           //???
            view.OptionsBehavior.Editable = false;                              //是否允许用户编辑单元格
            view.OptionsView.AllowCellMerge = true;

          
        }

        /// <summary>
        /// 加载所有设备类型
        /// </summary>
        private void LoadDTypeList()
        {
            this.cBoxDevice.Items.Clear();
            foreach (string strKey in c_Device.DeviceMsgGather.Keys)
            {
                int index = this.cBoxDevice.Items.Add(strKey);
            }

            this.cBoxDevice.SelectedItem = strDefaultDType;
        }

        private void InitBindingSourceTable(string strType)
        {
            foreach (objMsgDevStruct dev in c_Device.DeviceMsgGather[strType].DevList)
            {
                DataRow dr = dailyDataTable.NewRow();
                for (int i = 0; i < dailyDataTable.Columns.Count; i++)
                {

                    if (i == 0)
                        dr[0] = dev.DevName;
                    else
                    {
                        if (CheckAttiIsVisable((string)this.cBoxDevice.SelectedItem, dev.DevName, bandedGridView1.Bands.IndexOf(bandedGridView1.Columns[i].OwnerBand.ParentBand) - 1))
                        {
                            dr[i] = "0"; 
                        }
                        else
                        {
                            dr[i] = "**";
                        }
                    }

                }
                dailyDataTable.Rows.Add(dr);
            }

        }

        private bool CheckAttiIsVisable(string strDType, string strDName, int attIndex)
        {
            foreach (objMsgDevStruct device in c_Device.DeviceMsgGather[strDType].DevList)
            {
                if (device.DevName == strDName)
                {
                    return device.AnalogSet[attIndex] != -1 ? true : false;
                }
            }

            return false;
        }

        /// <summary>
        /// 加载对应设备类型属性
        /// </summary>
        /// <param name="strDType"></param>
        private void LoadProListForDType(string strDType)
        {
            this.listView_Pro.Items.Clear();
            foreach (objMsgAttriStruct attri in c_Device.DeviceMsgGather[strDType].ArrtiList)
            {
                ListViewItem viewItem = new ListViewItem(attri.AttriName);
                if (attri.AnalogType == AnalogCodeType.None) continue;
                viewItem.SubItems.Add(attri.AttriName);
                this.listView_Pro.Items.Add(viewItem);
                viewItem.Tag = attri.AttriName + "(" + attri.UnitName + ")";
                viewItem.Checked = true;
            }
        }

        private void GetDailyReportTimeListForDType(string strDType)
        {

        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (strPerSelectGroupCaption != string.Empty)
            {
                MySql.InsertUserScanT("设备浏览记录", strPerSelectGroupCaption + "实时值", sTime, DateTime.Now, "实时值");
            }
            else
            {
                MySql.InsertUserScanT("设备浏览记录", strNowSelDType + "实时值", sTime, DateTime.Now, "实时值");
            }
            base.OnClosing(e);
        }

        private DateTime sTime = DateTime.Now;
        string strNowSelDType;
        /// <summary>
        /// 设备类型改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CBoxDevice_SelectedIndexChanged(object sender, EventArgs e)
        {
            strNowSelDType = (string)this.cBoxDevice.SelectedItem;
            if (strNowSelDType == strPerSelectGroupCaption)
                return;

            if (strPerSelectGroupCaption != string.Empty)
            {
                MySql.InsertUserScanT("设备浏览记录", strPerSelectGroupCaption + "日报表", sTime, DateTime.Now, "实时值");
            }

            if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible == true)
            {
                SplashScreenManager.CloseForm();
            }
            SplashScreenManager.ShowForm(typeof(ViewWaitForm));
            SplashScreenManager.Default.SetWaitFormCaption("正在查询" + strNowSelDType + "日报表数据");
            SplashScreenManager.Default.SetWaitFormDescription("请稍后");
            dt = DateTime.Now;

            dailyDataTable = new DataTable();
            strPerSelectGroupCaption = strNowSelDType;
            view.BeginUpdate();
            view.BeginDataUpdate();
            view.Bands.Clear();
            view.Columns.Clear();

            GridBand gBand = bandedGridView1.Bands.AddBand("设备名称");
            gBand.Fixed = FixedStyle.Left;
            gBand.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            //gBand.Width = 100;
            BandedGridColumn bgc = new BandedGridColumn();
           
            bgc.FieldName = "设备名称";
            gBand.Columns.Add(bgc);
            dailyDataTable.Columns.Add("设备名称");
            bgc.VisibleIndex = view.Columns.Count;
            bgc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
            bgc.AppearanceCell.BackColor = Color.LemonChiffon;

            foreach (objMsgAttriStruct attri in c_Device.DeviceMsgGather[strNowSelDType].ArrtiList)
            {
                if (attri.AnalogType != AnalogCodeType.None)
                {
                    gBand = bandedGridView1.Bands.AddBand(attri.AttriName + "(" + attri.UnitName + ")");
                    gBand.Name = attri.AttriName + "(" + attri.UnitName + ")";
                }
                else
                {
                    continue;
                    //gBand = bandedGridView1.Bands.AddBand(attri.AttriName);
                    //gBand.Name = attri.AttriName;
                }
                gBand.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
              

                string strHead1 = string.Empty;
                string strHead2 = string.Empty;
                string strHead3 = string.Empty;

                c_Device.GetDailyTableHeadStr(strNowSelDType, attri.AttriName, ref strHead1, ref strHead2, ref strHead3);
                string[] customProArr_temp = new string[] { strHead1, strHead2, strHead3 };
                for (int i = 0; i < 3; i++)
                {
                    GridBand gBandChild = gBand.Children.AddBand(customProArr_temp[i]);
                    dailyDataTable.Columns.Add(attri.AttriName + "(" + attri.UnitName + ")" + customProArr_temp[i]);
                    gBandChild.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
//                    gBandChild.Width = 60;
                    bgc = new BandedGridColumn();

                    bgc.FieldName = attri.AttriName + "(" + attri.UnitName + ")" + customProArr_temp[i];
                    gBandChild.Columns.Add(bgc);
                    bgc.VisibleIndex = view.Columns.Count;
                    bgc.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                    bgc.AppearanceCell.BackColor = Color.LemonChiffon;
                    bgc.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                    bgc.AppearanceCell.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                    if (customProArr_temp[i] == string.Empty)
                        gBandChild.Visible = false;

                    SplashScreenManager.Default.SetWaitFormDescription("执行时间" + DateTime.Now.Subtract(dt).Hours +":"+ DateTime.Now.Subtract(dt).Minutes +":"+ DateTime.Now.Subtract(dt).Seconds);
                }
            }

            colCount = (view.Bands.Count - 1) * 3 + 1;

            InitBindingSourceTable(strNowSelDType);
            this.bandedGridView1.OptionsView.RowAutoHeight = true;
            this.bandedGridView1.LayoutChanged();
            //this.bandedGridView1.OptionsBehavior.AllowPixelScrolling = DevExpress.Utils.DefaultBoolean.True;
           

            SearchDailyRecord();
            WaitForData();

            view.EndDataUpdate();
            view.EndUpdate();
            
            GetDailyReportTimeListForDType(strNowSelDType);
            LoadProListForDType(strNowSelDType);
            if (SplashScreenManager.Default != null && SplashScreenManager.Default.IsSplashFormVisible == true)
            {
                SplashScreenManager.CloseForm();
            }

            this.DevDataGrid.DataSource = dailyDataTable;

            bandedGridView1.Columns[0].BestFit();
            this.DevDataGrid.RefreshDataSource();

            sTime = DateTime.Now;
        }

        /// <summary>
        /// 填充数据
        /// </summary>
        private void FillData()
        {
            view.AddNewRow();
        }

        /// <summary>
        /// 日报表时间改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CBoxTime_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void SetProCheckState()
        {
        }

        /// <summary>
        /// 属性选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListView_Pro_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (bandedGridView1.Bands[e.Item.Tag as string] != null)
            {
                if (e.Item.Checked)
                {
                    bandedGridView1.Bands[e.Item.Tag as string].Visible = true;
                }
                else
                {
                    bandedGridView1.Bands[e.Item.Tag as string].Visible = false;
                }
            }

            if (listView_Pro.CheckedItems.Count == listView_Pro.Items.Count)
            {
                checkBox_all.CheckState = CheckState.Checked;//全选
            }
            else if (listView_Pro.CheckedItems.Count == 0)
            {
                checkBox_all.CheckState = CheckState.Unchecked;//全不选
            }
            else
            {
                checkBox_all.CheckState = CheckState.Indeterminate;//半全选
            }
            //WaitForData();
        }

        /// <summary>
        /// 属性全选事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_All_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_all.Checked)
            {
                if (checkBox_all.CheckState != CheckState.Indeterminate)
                {
                    foreach (ListViewItem item in listView_Pro.Items)
                    {
                        if (item != null && !item.Checked)
                            item.Checked = true;
                    }
                }
            }
            else
            {
                foreach (ListViewItem item in listView_Pro.Items)
                {
                    if (item != null && item.Checked)
                        item.Checked = false;
                }
            }
        }

        /// <summary>
        /// 时间日期改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DtPicker_ValueChanged(object sender, EventArgs e)
        {
            SearchDailyRecord();
            WaitForData();
        }

        /// <summary>
        /// 查询对应设备对应日期日报表数据
        /// </summary>
        private void SearchDailyRecord()
        {
            objDate data = new objDate();
            data.year = dtPicker.Value.Year;
            data.month = (byte)dtPicker.Value.Month;
            data.day = (byte)dtPicker.Value.Day;
            dailyReport.ReadDailyReportValueList(data, (string)this.cBoxDevice.SelectedItem);
        }

        /// <summary>
        /// 等待并绑定数据
        /// </summary>
        private void WaitForData()
        {
            while (!dailyReport.Ready_DailyReportValueList)
            {
                //SplashScreenManager.Default.SetWaitFormDescription("执行时间" + DateTime.Now.Subtract(dt).Hours + ":" + DateTime.Now.Subtract(dt).Minutes + ":" + DateTime.Now.Subtract(dt).Seconds);
                if (dailyReport.DailyReportErrorFlag != 0)
                {
                    return;
                }

                Thread.Sleep(20);
            }

            int rowIndex = 0;

            if (!dailyReport.DailyReportMsgDevValue.ContainsKey((string)this.cBoxDevice.SelectedItem))
                return;

            foreach (DailyReportTable.objDailyReportMsgDev value in dailyReport.DailyReportMsgDevValue[(string)this.cBoxDevice.SelectedItem])
            {
                DataRow dr = dailyDataTable.Rows[rowIndex++];
                
                for (int i = 0; i < value.DevValueList.Count; i++)
                {
                    if (value.DevValueList[i].objset.AnalogName == "") continue;
                    if (CheckAttiIsVisable((string)this.cBoxDevice.SelectedItem, (string)dr[0], bandedGridView1.Bands.IndexOf(bandedGridView1.Columns[i * 3 + 1].OwnerBand.ParentBand) - 1))
                    {
                        dr[i * 3 + 1] = value.DevValueList[i].MaxValue.Value;
                        dr[i * 3 + 2] = value.DevValueList[i].MinValue.Value;
                        dr[i * 3 + 3] = value.DevValueList[i].AvrValue.Value;
                    }

                }
            }
            
            //this.bandedGridView1.BestFitColumns();
        }
        private void DisplayValue()
        {
            int rowIndex = 0;

            if (!dailyReport.DailyReportMsgDevValue.ContainsKey((string)this.cBoxDevice.SelectedItem))
                return;

            foreach (DailyReportTable.objDailyReportMsgDev value in dailyReport.DailyReportMsgDevValue[(string)this.cBoxDevice.SelectedItem])
            {
                DataRow dr = dailyDataTable.Rows[rowIndex++];

                for (int i = 0; i < value.DevValueList.Count; i++)
                {
                    if (value.DevValueList[i].objset.AnalogName == "") continue;
                    if (CheckAttiIsVisable((string)this.cBoxDevice.SelectedItem, (string)dr[0], bandedGridView1.Bands.IndexOf(bandedGridView1.Columns[i * 3 + 1].OwnerBand.ParentBand) - 1))
                    {
                        dr[i * 3 + 1] = value.DevValueList[i].MaxValue.Value;
                        dr[i * 3 + 2] = value.DevValueList[i].MinValue.Value;
                        dr[i * 3 + 3] = value.DevValueList[i].AvrValue.Value;
                    }

                }
            }
        }
        private void DisplayTimeAndValue()
        {
            int rowIndex = 0;

            if (!dailyReport.DailyReportMsgDevValue.ContainsKey((string)this.cBoxDevice.SelectedItem))
                return;

            foreach (DailyReportTable.objDailyReportMsgDev value in dailyReport.DailyReportMsgDevValue[(string)this.cBoxDevice.SelectedItem])
            {
                DataRow dr = dailyDataTable.Rows[rowIndex++];

                for (int i = 0; i < value.DevValueList.Count; i++)
                {
                    if (value.DevValueList[i].objset.AnalogName == "") continue;
                    if (CheckAttiIsVisable((string)this.cBoxDevice.SelectedItem, (string)dr[0], bandedGridView1.Bands.IndexOf(bandedGridView1.Columns[i * 3 + 1].OwnerBand.ParentBand) - 1))
                    {
                        StringBuilder str = new StringBuilder();
                        str.Append(string.Format("{0}\r\n",value.DevValueList[i].MaxValue.Value.ToString()));
                        str.Append(string.Format("{0}",MySql.Time_tToDateTime(value.DevValueList[i].MaxTime).ToString()));
                        dr[i * 3 + 1] = str;
                        str = new StringBuilder();
                        str.Append(string.Format("{0}\r\n", value.DevValueList[i].MinValue.Value.ToString()));
                        str.Append(string.Format("{0}", MySql.Time_tToDateTime(value.DevValueList[i].MinTime).ToString()));
                        dr[i * 3 + 2] = str;
                        dr[i * 3 + 3] = value.DevValueList[i].AvrValue.Value;
                    }
                }
            }
        }

        private void bandedGridView1_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e)
        {

        }

        private void bandedGridView1_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            GridCellInfo cell = e.Cell as GridCellInfo;
            int row = e.RowHandle;
            string colname = cell.Column.FieldName;
            int k = colname.IndexOf("(");
            if (k > 0) colname = colname.Remove(k);
            string DevName = dailyDataTable.Rows[row][0].ToString(); //设备名称
            if (cell.Column.FieldName == "设备名称") return;
            if (cell.Column.FieldName.Contains("时间")) return;
            if (cell.CellValue == null) return;
            string cellstr = cell.CellValue.ToString();
            int l = cellstr.IndexOf("\r");
            if (l > 0) cellstr = cellstr.Remove(l);
            if (cellstr.Contains("*") || cellstr.Contains("-")) return;
            if (cellstr.Contains("↑") || cellstr.Contains("↓")) return;
            if (cellstr.Contains("未知") || cellstr.Contains("未测试")) return;
            if (cellstr == "") return;
            float value = float.Parse(cellstr.ToString());
            AnalogObj tt = c_Device.GetAnalogDevNo(strNowSelDType, DevName, colname);
            if (tt.type == AnalogCodeType.None) { }
            else
            {
                objSingleAnalogStruct a = c_Device.GetSingleAnalogConfig(strNowSelDType, DevName, colname);
                if (value > a.UpperThreshold || value < a.LowerThreshold)
                {
                    cell.Appearance.ForeColor = CommonColors.GetCriticalColor(DevExpress.LookAndFeel.UserLookAndFeel.Default);
                }
            }
        }

        string  GetTimeStr(string DevName,string Attri)
        {
            string Astr = Attri;
            int k = Astr.IndexOf("(");
            if (k > 0) Astr = Astr.Remove(k);
            if (dailyReport.DailyReportMsgDevValue.ContainsKey(strNowSelDType))
            {
                foreach (DailyReportTable.objDailyReportMsgDev value in dailyReport.DailyReportMsgDevValue[strNowSelDType])
                {
                    if(value.DevName == DevName)
                    {
                        for(int i = 0;i<value.DevValueList.Count;i++)
                        {
                            if(value.DevValueList[i].AttriName == Astr)
                            {
                                if (Attri.Contains("调整最高") || Attri.Contains("最大值") || Attri.Contains("空闲最高"))
                                    return MySql.Time_tToDateTime(value.DevValueList[i].MaxTime).ToString();
                                else if (Attri.Contains("调整最低") || Attri.Contains("最小值") || Attri.Contains("空闲最低"))
                                    return MySql.Time_tToDateTime(value.DevValueList[i].MinTime).ToString();
                            }
                        }
                    }
                }
            }
            return "";
        }

        private Point mp;
        private void DevDataGrid_MouseMove(object sender, MouseEventArgs e)
        {
            GridHitInfo info = this.bandedGridView1.CalcHitInfo(e.Location);
            if (info.RowHandle < 0 || info.Column == null)
            {
                toolTip1.Hide(this);
                mp = e.Location;
                return;
            }
            if (mp == e.Location) return;
            else mp = e.Location;
            string DevName = dailyDataTable.Rows[info.RowHandle][0].ToString();
            string Attri = info.Column.FieldName;
            string TimeStr = GetTimeStr(DevName, Attri);
            //dailyDataTable.Rows[info.RowHandle][info.Column.Caption].ToString();
            int k = Attri.IndexOf("(");
            if (k > 0) Attri = Attri.Remove(k);
            if (Attri == "" || Attri == "设备名称" || !info.InRowCell)
            {
                toolTip1.Hide(this);
                mp = e.Location;
                return;
            }
            objSingleAnalogStruct a = c_Device.GetSingleAnalogConfig(strNowSelDType, DevName, Attri);
            StringBuilder txt = new StringBuilder();
            txt.Append(string.Format("类型:{0}\r\n", strNowSelDType));
            txt.Append(string.Format("设备名:{0}\r\n", DevName));
            txt.Append(string.Format("属性:{0}\r\n", Attri));
            txt.Append(string.Format("上限:{0}\r\n", a.UpperThreshold.ToString()));
            txt.Append(string.Format("下限:{0}\r\n", a.LowerThreshold));
            if (TimeStr != "" && !TimeStr.Contains("1970")) txt.Append(string.Format("时间:{0}", TimeStr));
            toolTip1.AutoPopDelay = 5000;
            //toolTip1.InitialDelay = 1000;
            //toolTip1.ReshowDelay = 100;
            toolTip1.ShowAlways = true;
            toolTip1.Show(txt.ToString(), this, e.Location);
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.CheckState == CheckState.Checked)
                DisplayTimeAndValue();
            else DisplayValue();
        }

        private void bandedGridView1_CalcRowHeight(object sender, RowHeightEventArgs e)
        {
            if (e.RowHandle >= 0)
                if (checkBox2.CheckState == CheckState.Checked)
                    e.RowHeight = 60;
                else e.RowHeight = 20;
        }
    }
}